<template>
    <div class="create-page">
        <NavBar navbarTitle="填写订单"></NavBar>
        <!-- 订单收货地址信息 -->
        <div class="page-address">
            <Icon name="location-o" color="#9195a3" size="20"/>
            <div class="address-info">
                <span class="info-item info-user">{{addressInfo.linkUser + " " + addressInfo.linkPhone}}</span>
                <span class="info-item info-address">{{addressInfo.linkAddress}}</span>
            </div>
            <Icon name="arrow" color="#9195a3" size="12"/>
        </div>
        <!-- 订单商品信息 -->
        <div class="page-product">
            <div class="product-item" v-for="item,index in productInfo" :key="index">
                <img class="item-img" :src="item.productImg[0]" alt="商品图片" title="图片">
                <div class="item-info">
                    <div class="info-productName">{{ item.productName }}</div>
                    <div class="info-productAttr">
                        <span class="productAttr-item">{{ item.commodityStandardStr }}</span>
                    </div>
                    <div class="info-productPrice">
                        <span class="price">￥{{ item.productPrice.toFixed(2) }}</span>
                        <span class="number">{{ "x" + item.commodityCount }}</span>
                    </div>
                </div>
            </div>
        </div>
        <!-- 订单配送时间、订单备注 -->
        <div class="page-deliver">
            <div class="deliver-item">
                <span class="item-time">配送时间</span>
                <div class="item-time-options">
                    <span class="options-tip">时间不限(周一至周五)</span>
                    <Icon name="arrow" color="#9195a3"></Icon>
                </div>
            </div>
            <div class="deliver-item">
                <span class="item-time">订单备注</span>
                <div class="item-time-options">
                    <input class="options-input" type="text" placeholder="建议留言前先与商家沟通确认" v-model="orderRemark">
                </div>
            </div>
        </div>
        <!-- 商品总价、运费部分 -->
        <div class="page-fee">
            <div class="fee-item">
                <span class="item-price">订单总价</span>
                <span class="item-num">￥{{ productTotalPrice.toFixed(2) }}</span>
            </div>
            <div class="fee-deliver">
                <span class="deliver-tip">订单运费</span>
                <span class="deliver-num">￥{{ deliveryFee.toFixed(2) }}</span>
            </div>
        </div>
        <!-- 底部固定功能区 -->
        <div class="page-functional">
            <span class="functional-totalPrice">￥{{ (productTotalPrice + deliveryFee).toFixed(2) }}</span>
            <van-button class="functional-btn" type="primary" size="small" @click="sendOrder_btn">提交订单</van-button>
        </div>
    </div>
</template>

<script setup lang="ts">
//引入vue
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
//@ts-ignore引入navbar组件
import NavBar from "@/components/NavBar/NavBar.vue";
//引入vant组件
import { Icon, Button as VanButton, showToast } from "vant";
//@ts-ignore引入请求函数
import { reqUserAddressList } from "@/api/user/index.ts";
//@ts-ignore引入用户仓库
import { useUserStore } from "@/store/userStore.ts";
const userStore = useUserStore();
//引入mitt全局事件通信插件
import mitt from "@/utils/eventBus";
//引入vue-router
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
//引入请求api
import { reqSaveUserOrder, reqSaveProductOrder, reqSaveProductOrderBatch } from "@/api/order/index";


//其它组件传递过来的创建订单数据
let addressInfo = reactive({
    linkUser:"",
    linkPhone:"",
    linkAddress:""
});
let productInfo = ref([]);
//商品总价
let productTotalPrice = ref(0);
let deliveryFee = ref(0);  //配送费 随机(8 - 15) * 商品数量
//订单备注
let orderRemark = ref("");


//提交订单按钮(废弃)
async function submitOrder_btn () {
    let userId = userStore.userInfo.id || JSON.parse(localStorage.getItem("userInfo")).id;
    let totalPrice = Number((productTotalPrice.value + deliveryFee.value).toFixed(2));
    //参数整理
    let productOrderList = productInfo.value.map(item => {
        return {
            commodityId:item.commodityId,
            userId:userId,
            commodityStandardId:item.commodityStandardId,
            commodityStandardStr:item.commodityStandardStr,
            commodityCount:item.commodityCount,
            orderTotalPrice:Number(((item.productPrice * item.commodityCount) + (deliveryFee.value/productInfo.value.length)).toFixed(2)),
            orderState:"未支付",
            linkUser:addressInfo.linkUser,
            linkPhone:addressInfo.linkPhone,
            linkAddress:addressInfo.linkAddress,
            orderRemark:orderRemark.value === '' ? null : orderRemark.value,
            logisticsInfo:"暂无物流信息"
        }
    })
    let userOrderInfo = {
        userId:userId,
        commodityOrderCount:productInfo.value.length,
        commodityFee:productTotalPrice.value,
        deliveryFee:Number(deliveryFee.value.toFixed(2)),
        actualAmount:0,
        userOrderState:"未支付",
        linkUser:addressInfo.linkUser,
        linkPhone:addressInfo.linkPhone,
        linkAddress:addressInfo.linkAddress,
        logisticsInfo:"暂无物流信息",
        orderRemark:orderRemark.value === '' ? null : orderRemark.value,
        productOrderList:productOrderList
    }
    //发请求创建订单
    let res = await reqSaveUserOrder(userOrderInfo);
    console.log('创建用户订单api',res);
    //进行路由跳转
    //router.push("/orderDetail");
    console.log(userOrderInfo);
}
//提交订单按钮
const sendOrder_btn = async () => {
    let userId = userStore.userInfo.id || JSON.parse(localStorage.getItem("userInfo")).id;
    let totalPrice = Number((productTotalPrice.value + deliveryFee.value).toFixed(2));
    //参数整理
    let productOrderList = productInfo.value.map(item => {
        return {
            commodityId:item.commodityId,
            userId:userId,
            commodityStandardId:item.commodityStandardId,
            commodityStandardStr:item.commodityStandardStr,
            commodityCount:item.commodityCount,
            orderTotalPrice:Number(((item.productPrice * item.commodityCount) + (deliveryFee.value/productInfo.value.length)).toFixed(2)),
            orderState:"未支付",
            linkUser:addressInfo.linkUser,
            linkPhone:addressInfo.linkPhone,
            linkAddress:addressInfo.linkAddress,
            orderRemark:orderRemark.value === '' ? '暂无备注' : orderRemark.value,
            logisticsInfo:"暂无物流信息"
        }
    })
    //向服务器发请求
    if(productOrderList.length === 1){
        //创建一条商品订单
        let res = await reqSaveProductOrder(productOrderList[0]);
        if(res.code === 200){
            //路由跳转
            router.push({path:"/orderDetail",query:{orderIds:res.result.orderIds[0]}});
            showToast("订单创建成功!");
        }
        console.log("订单创建api",res);
    } else if (productOrderList.length > 1) {
        //批量创建商品订单(购物车渠道创建订单)
        let res = await reqSaveProductOrderBatch(productOrderList);
        if(res.code === 200){
            //路由跳转
            router.push({path:"/orderDetail",query:{orderIds:res.result.toString()}});
            showToast("订单批量创建成功!");
        }
        console.log('订单批量创建api',res);
    }
}

//获取用户的地址信息(从购物车创建订单时没有收货地址信息)
async function getUserAddress () {
    let res = await reqUserAddressList(userStore.userInfo.id || JSON.parse(localStorage.getItem("userInfo")).id);
    if(res.code === 200){
        res.result.forEach(item => {
            if(item.defaultAddress){
                addressInfo.linkUser = item.linkUser;
                addressInfo.linkPhone = item.linkPhone;
                addressInfo.linkAddress = item.linkAddress;
            }
        })
    }
    console.log('获取用户地址列表信息api',res);
}

//获取别的组件传递过来的订单数据
const getOrderInfo = () => {
    mitt.on("orderInfo",(orderInfo:any) => {
        if(orderInfo.addressInfo !== undefined){
            addressInfo.linkUser = orderInfo.addressInfo.linkUser;
            addressInfo.linkPhone = orderInfo.addressInfo.linkPhone;
            addressInfo.linkAddress = orderInfo.addressInfo.linkAddress;
        } else {
            getUserAddress();
        }
        productInfo.value = orderInfo.productInfo;
        //console.log(orderInfo);
        //生成费用计算
        let productFee = 0;
        orderInfo.productInfo.forEach(item => {
            productFee += (item.productPrice * item.commodityCount);
        })
        productTotalPrice.value = productFee;
        deliveryFee.value = (Math.random() * (15 - 8) + 8) * productInfo.value.length;
    })
}

//vue生命周期
onMounted(() => {
    //全局通信事件绑定监听函数
    getOrderInfo();
})
onBeforeUnmount(() => {
    //销毁全局事件总线
    mitt.off("orderInfo");
})
</script>

<style lang="less" scoped>
.create-page{
    width: 375px;
    height: calc(100vh - 50px - 50px);
    position: relative;
    top:47px;
    background:#eff2f5;
    overflow: auto;
    /**订单收货地址信息 */
    .page-address{
        width:360px;
        height:70px;
        margin:0 auto;
        padding:10px;
        box-sizing:border-box;
        background:#fff;
        border-radius:5px;
        display:flex;
        justify-content:space-between;
        align-items:center;
        .address-info{
            width:300px;
            display:flex;
            flex-direction:column;
            .info-item{
                font-size:12px;
                color:#9195a3;
                margin:3px 0;
            }
        }
    }
    /**订单商品信息 */
    .page-product{
        width: 360px;
        margin: 10px auto;
        border-radius: 5px;
        background: #fff;
        .product-item{
            width: 100%;
            height: 100px;
            padding: 9px;
            margin: 5px 0;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            .item-img{
                width: 80px;
                height: 80px;
                margin-right: 10px;
            }
            .item-info{
                width: 250px;
                height: 80px;
                display: flex;
                flex-direction: column;
                .info-productName{
                    flex: 2;
                    font-size: 16px;
                    color: #000;
                }
                .info-productAttr{
                    flex:1;
                    .productAttr-item{
                        font-size: 12px;
                        padding: 2px 4px;
                        color: #9195a3;
                        background: #f1f1f4;
                        border-radius: 3px;
                    }
                }
                .info-productPrice{
                    flex:1;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    .price{
                        font-size: 14px;
                        color: #f00;
                    }
                    .number{
                        font-size: 12px;
                        color: #000;
                    }
                }
            }
        }
    }
    /**订单配送时间、订单备注 */
    .page-deliver{
        width: 360px;
        margin: 10px auto;
        padding: 8px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        border-radius: 5px;
        background: #fff;
        .deliver-item{
            width: 100%;
            height: 35px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 13px;
            .options-input{
                width: 250px;
                text-align: end;
                border: none;
            }
            .options-input::placeholder{
                color: #bec0c5;
            }
        }
    }
    /**订单配送时间、订单备注 */
    .page-fee{
        width: 360px;
        margin: 10px auto;
        padding: 8px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        border-radius: 5px;
        background: #fff;
        .fee-item,.fee-deliver{
            width: 100%;
            height: 35px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 13px;
        }
    }
    /**底部固定功能区 */
    .page-functional{
        width: 375px;
        height: 50px;
        background: #fff;
        padding: 3px 10px;
        box-sizing: border-box;
        position: fixed;
        bottom: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .functional-totalPrice{
            font-size: 16px;
            color: #f00;
        }
        .functional-btn{
            width: 110px;
        }
    }
}
</style>